package com.kuaimacode.kframework.api.controller.user;


import com.github.pagehelper.PageInfo;
import com.kuaimacode.kframework.api.controller.BaseController;
import com.kuaimacode.kframework.api.service.*;
import com.kuaimacode.kframework.api.service.user.OrderService;
import com.kuaimacode.kframework.api.vo.request.FeedbackReq;
import com.kuaimacode.kframework.api.vo.response.ComplainMasterResp;
import com.kuaimacode.kframework.common.JsonResult;
import com.kuaimacode.kframework.constants.PageConstants;
import com.kuaimacode.kframework.exception.ErrorEnum;
import com.kuaimacode.kframework.exception.ServerInternalErrorException;
import com.kuaimacode.kframework.mybatis.models.index.Feedback;
import com.kuaimacode.kframework.mybatis.models.user.Order;
import com.kuaimacode.kframework.mybatis.models.user.User;
import com.kuaimacode.kframework.mybatis.models.user.UserCertifacate;
import com.kuaimacode.kframework.service.DictService;
import com.kuaimacode.kframework.util.DictUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/feedback")
@Api(tags = "投诉反馈",description = "投诉反馈api")
public class FeedbackController extends BaseController {

    @Autowired
    private FeedbackService feedbackService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private UserMasterService masterService;

    @Autowired
    private UserService userService;

    @Autowired
    private DictService dictService;

    @Autowired
    private UserCertifacateService certifacateService;

    @Autowired
    private UploadService uploadService;


    @ApiOperation(value = "查询投诉反馈列表(分页)", notes="查询投诉反馈列表")
    @GetMapping("/listPage/{type}")
    @ApiImplicitParam(name = "type", value = "类型 1 投诉 2 反馈", required = true, dataType = "string")
    public JsonResult<Feedback> index(@RequestParam(value = "pageNum", required = true, defaultValue = PageConstants.PAGE_NUM+"") int pageNum,
                            @RequestParam(value = "pageSize", required = true, defaultValue = PageConstants.PAGE_SIZE+"") int pageSize,
                            @PathVariable String type) {
        PageInfo<Feedback> pageInfo = feedbackService.queryUserFeedbackListPage(pageNum, pageSize,getUserId(),type);
        return JsonResult.success(pageInfo.getList());
    }


    @ApiOperation(value = "新增投诉/反馈", notes="新增投诉/反馈，图片上传请调用/upload/uploadImg。订单投诉type请传1，反馈建议type请传2")
    @PostMapping("/add")
    @ApiImplicitParam(name = "feedbackReq", value = "feedback实体", required = true, dataType = "FeedbackReq")
    public JsonResult add(@RequestBody FeedbackReq feedbackReq, HttpServletRequest request) {
        Optional.ofNullable(feedbackReq.getType()).orElseThrow(() -> new ServerInternalErrorException(ErrorEnum.PARAM_VALID_ERROR));
        if(feedbackReq.getType() == 1){
            //订单投诉
            List<Feedback> lists =  feedbackService.findByOrderId(feedbackReq.getOrderId());
            if(lists.size() >0){
                throw new ServerInternalErrorException(ErrorEnum.ORDER_FEEDBACK_HAS_EXIST);
            }
        }
        Feedback feedback = feedbackService.saveFeedback(feedbackReq,getUserId());
        Map map = new HashMap();
        map.put("id",feedback.getId());
        return JsonResult.success(map);
    }


    @ApiOperation(value = "查询投诉/反馈子类型", notes="查询投诉/反馈子类型")
    @GetMapping("/getSubType/{type}")
    @ApiImplicitParam(name = "type", value = "类型 1 投诉 2 反馈", required = true, dataType = "string")
    public JsonResult getSubType(@PathVariable String type) {
        String dictName = "FEEDBACK_TYPE";
        if("1".equals(type)) dictName = "COMPLAIN_TYPE";
        Map<String,String> map = DictUtil.keyValueList(dictName);

        return JsonResult.success(map);
    }


    @ApiOperation(value = "根据id/流水号查询详细信息", notes="根据id/流水号查询详细信息")
    @GetMapping("/getDetail/{id}")
    @ApiImplicitParam(name = "id", value = "id/流水号", required = true, dataType = "string")
    public JsonResult<Feedback> getDetail(@PathVariable String id) {

        Feedback feedback = feedbackService.getById(id);
        String dictName = "FEEDBACK_TYPE";
        if(feedback!=null){

            if(1==feedback.getType()){
                dictName = "COMPLAIN_TYPE";
                //订单投诉
                Order order = orderService.getById(feedback.getOrderId());
                Optional.ofNullable(order).ifPresent(o->{
                    feedback.setOrderNo(o.getOrderNo());
                    feedback.setOrderTime(o.getCreateAt());
                    ComplainMasterResp master = complainMaster(o.getMasterId());
                    feedback.setMasterHeadPic(master.getHeadPic());
                    feedback.setMasterName(master.getName());
                    feedback.setMasterPhone(master.getPhone());
                });
            }
            feedback.setSubTypeName(DictUtil.enumValue(dictName,feedback.getSubType()));
        }else{
            return JsonResult.failure("未查询到编号对应的投诉信息");
        }
        return JsonResult.success(feedback);
    }

    public ComplainMasterResp complainMaster( Long masterId){
        ComplainMasterResp masterResp = masterService.findMasterData(masterId);
        if (masterResp!=null&&StringUtils.isNotEmpty(masterResp.getHeadPic())){
            masterResp.setHeadPic(uploadService.getPicUrlPath(masterResp.getHeadPic()));
        }
//        User user = userService.getById(masterId);
//        if (user != null){
//            masterResp.setPhone(user.getPhone());
//            UserCertifacate certifacate = certifacateService.selectByUserId(user.getId());
//            if (certifacate != null) {
//                String headPic = certifacate.getHeadPic();
//                if (StringUtils.isNotEmpty(headPic)){
//                    headPic = uploadService.getPicUrlPath(headPic);
//                }
//                masterResp.setHeadPic(headPic);
//                String name = certifacate.getName();
//                masterResp.setName(name);
//
//            }
//        }

        return masterResp;
    }


}
